package cn.middle.edge.remote;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.middle.common.result.ApiResponse;
import com.middle.common.util.GsonUtil;

import cn.middle.edge.bussiness.HairDownHandler;
import cn.middle.edge.config.ApplicationContextUtil;
import cn.middle.edge.entity.HairDown;
import cn.middle.edge.server.api.CallApi;
import cn.middle.edge.server.api.DefaultServerPluginManager;
import cn.middle.edge.server.api.ServerPluginManager;
import cn.middle.edge.server.dto.DoorUserDto;
import cn.middle.edge.server.rust.CallResult;
import cn.middle.edge.service.HairDownService;
import cn.middle.remote.Buffer;
import cn.middle.remote.edge.EdgeListener;
import cn.middle.remote.functions.CallbackEvent;
import cn.middle.remote.serialization.TypeGenericity;

/**
 * 测试监听器
 * @author KING
 *
 */
public class DataListener implements EdgeListener {
	
	private static final Logger logger = LoggerFactory.getLogger(DataListener.class);
	
	//服务调用接口
	//private ServerPluginManager apiManager = DefaultServerPluginManager.of();
	
			
	/**
	 *  测试样例
	 */
	@SuppressWarnings("rawtypes")
	private final static Map<String,HairDownHandler> HANDLERS = new HashMap<>();
	
	static {
		HANDLERS.put("addUser", new HairDownHandler<DoorUserDto>() {

			@SuppressWarnings("unchecked")
			@Override
			public ApiResponse<DoorUserDto> handler(String interfaceName, Buffer buffer) {
				
				
				DoorUserDto dto = buffer.to(new TypeGenericity<DoorUserDto>() {});
				HairDown down = new HairDown();
				down.setMessageId(buffer.getMsgId());
				down.setInterfaceName(interfaceName);
				down.setReceptionTime(new Date());
				down.setReceptionData(dto != null ? GsonUtil.toJson(dto) : "");
				
				ApiResponse<DoorUserDto> result = null;
				try {
					if(dto != null) {	
						
						//根据服务代码查找到相应业务处理的插件，将数据下发到第三方系统服务
						CallApi api = DefaultServerPluginManager.of().findCallApi(dto.getServerCode());
						if(api == null) {
							result = ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "服务插件未实始化，请您注意检查");
						}else {
							//根据
							CallResult<DoorUserDto> callResult = api.addUser(dto);
							if(callResult != null) {
								if(callResult.isCallStatus()) {
									result = ApiResponse.successWithData(callResult.getData());
								}else {
									result = ApiResponse.FailCustomWithMessage(String.valueOf(-1000),callResult.described);
								}
							}else {
								result = ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "服务调用返回为空！");
							}
						}
						
						
					}
				}catch(Exception e) {
					result = ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "服务调用异常，请您注意检查");

					logger.error(e.getMessage(),e);
				}
				
				
				down.setHandlerData(GsonUtil.toJson(result));
				down.setReportTime(new Date());
				
				HairDownService service = ApplicationContextUtil.getBean(HairDownService.class) ;
				//保存调用数据到下发表
				service.save(down);
				//返回
				return result;
			}
		});
		
		HANDLERS.put("deleteUser", new HairDownHandler<Object>() {

			@SuppressWarnings("unchecked")
			@Override
			public ApiResponse<Object> handler(String interfaceName, Buffer buffer) {
				String id = buffer.to(new TypeGenericity<String>() {});
				if(id.equals("1")) {
					//TODO 业务处理将用户数据，比如将数据下发到第三方系统服务查询。获取返回信息
					
					//返回
					return ApiResponse.successWithData(true);
				}
				return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "删除失败！");
			}
		});
		
		HANDLERS.put("findById", new HairDownHandler<Object>() {

			@SuppressWarnings("unchecked")
			@Override
			public ApiResponse<Object> handler(String interfaceName, Buffer buffer) {
				String id = buffer.to(new TypeGenericity<String>() {});
				if(id.equals("1")) {
					//TODO 业务处理将用户数据，比如将数据发送到第三方系统服务
					DoorUserDto dto = new DoorUserDto();
					dto.setId(1L);
					dto.setName("测试人员");
					dto.setPhone("123456789");
					dto.setSex(Byte.parseByte("1"));
					return ApiResponse.successWithData(dto);
				}
				return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "查询失败,未找到相关信息！");
			}
		});
	}
	
	
	@Override
	public void connectAfter(Integer clientId, boolean state) {
		logger.info("connectAfter ---> {}" , state);
	}

	@Override
	public void exception(Throwable e) {
		logger.error(e.getMessage(),e);

	}

	@Override
	public void connectLost(Integer clientId, int reson) {
		logger.info("connectLost ---> {}" , reson);
	}

	@Override
	public void ack(String msgId) {
		//返回的ACK
		logger.info("ack ---> {}" , msgId);
	}

	
	/**
	 * 接收应用端下发数据
	 */
	@Override
	public void hairDown(CallbackEvent callEvent, String interfaceName, Buffer buffer) {
		
		if(HANDLERS.containsKey(interfaceName)) {
			@SuppressWarnings("unchecked")
			ApiResponse<Object> apiResponse = HANDLERS.get(interfaceName).handler(interfaceName, buffer);
			if(apiResponse != null) {
				//回复数据给调用者
				callEvent.reply(apiResponse);
			}
		}else {
			//回复数据给调用者
			callEvent.reply(ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "接口未定义"));
		}
		
		//回复数据给调用者
		//callEvent.reply(ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "接口未定义"));
	}

	@Override
	public void loginResult(int code, String message) {
		logger.info("loginResult code ---> {} ---> {}" , code,message);
	}

}
